package com.geeaks.generator.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.geeaks.generator.enums.EnumDbType;
import com.geeaks.generator.model.DatabaseConfigBo;
import com.geeaks.generator.model.GenerateConfigBo;

public class ConfigHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(ConfigHelper.class);
	
	private static final String BASE_DIR = "config";
	
	private static final String CONFIG_FILE = "/sqlite3.db";
	
	public static void createEmptyFiles() throws Exception {
		File file = new File(BASE_DIR);
		if (!file.exists()) {
			file.mkdir();
		}
		File uiConfigFile = new File(BASE_DIR + CONFIG_FILE);
		if (!uiConfigFile.exists()) {
			createEmptyXMLFile(uiConfigFile);
		}
	}
	
	static void createEmptyXMLFile(File uiConfigFile) throws IOException {
		InputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = Thread.currentThread().getContextClassLoader().getResourceAsStream("sqlite3.db");
			fos = new FileOutputStream(uiConfigFile);
			byte[] buffer = new byte[1024];
			int byteread = 0;
			while ((byteread = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, byteread);
			}
		} finally {
			if (fis != null)
				fis.close();
			if (fos != null)
				fos.close();
		}
	}
	
	public static List<DatabaseConfigBo> loadDatabaseConfig() throws Exception {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			rs = stat.executeQuery("select * from dbs");
			List<DatabaseConfigBo> configs = new ArrayList<>();
			while (rs.next()) {
				String name = rs.getString("name");
				String value = rs.getString("value");
				DatabaseConfigBo databaseConfig = JSON.parseObject(value, DatabaseConfigBo.class);
				databaseConfig.setName(name);
				configs.add(databaseConfig);
			}
			return configs;
		} finally {
			if (rs != null)
				rs.close();
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static void saveDatabaseConfig(String name, DatabaseConfigBo dbConfig) throws Exception {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			ResultSet rs1 = stat.executeQuery("SELECT * from dbs where name = '" + name + "'");
			if (rs1.next()) {
				throw new RuntimeException("配置已经存在, 请使用其它名字");
			}
			String jsonStr = JSON.toJSONString(dbConfig);
			String sql = String.format("INSERT INTO dbs values('%s', '%s')", name, jsonStr);
			stat.executeUpdate(sql);
		} finally {
			if (rs != null)
				rs.close();
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static void deleteDatabaseConfig(String name) throws Exception {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			String sql = String.format("delete from dbs where name='%s'", name);
			stat.executeUpdate(sql);
		} finally {
			if (rs != null)
				rs.close();
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static GenerateConfigBo loadGeneratorConfig(String name) throws Exception {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			String sql = String.format("SELECT * FROM generator_config where name='%s'", name);
			logger.info("sql: ", sql);
			rs = stat.executeQuery(sql);
			GenerateConfigBo generatorConfig = null;
			if (rs.next()) {
				String value = rs.getString("value");
				generatorConfig = JSON.parseObject(value, GenerateConfigBo.class);
			}
			return generatorConfig;
		} finally {
			if (rs != null)
				rs.close();
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static List<GenerateConfigBo> loadGeneratorConfigs() throws Exception {
		Connection conn = null;
		Statement stat = null;
		ResultSet rs = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			String sql = String.format("SELECT * FROM generator_config");
			logger.info("sql: ", sql);
			rs = stat.executeQuery(sql);
			List<GenerateConfigBo> configs = new ArrayList<>();
			while (rs.next()) {
				String value = rs.getString("value");
				configs.add(JSON.parseObject(value, GenerateConfigBo.class));
			}
			return configs;
		} finally {
			if (rs != null)
				rs.close();
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static int deleteGeneratorConfig(String name) throws Exception {
		Connection conn = null;
		Statement stat = null;
		try {
			conn = ConnectionManager.getConnection();
			stat = conn.createStatement();
			String sql = String.format("DELETE FROM generator_config where name='%s'", name);
			logger.info("sql: {}", sql);
			return stat.executeUpdate(sql);
		} finally {
			if (stat != null)
				stat.close();
			if (conn != null)
				conn.close();
		}
	}
	
	public static String findConnectorLibPath(String dbType) {
		EnumDbType type = EnumDbType.valueOf(dbType);
		URL resource = Thread.currentThread().getContextClassLoader().getResource("logback.xml");
		logger.info("jar resource: {}", resource);
		if (resource != null) {
			try {
				File file = new File(resource.toURI().getRawPath() + "/../lib/" + type.getConnectorJarFile());
				return file.getCanonicalPath();
			} catch (Exception e) {
				throw new RuntimeException("找不到驱动文件，请联系开发者");
			}
		} else {
			throw new RuntimeException("lib can't find");
		}
	}
}
